package com.ecelin.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.ecelin.MainApplication;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 初始化SqlSessionFactory
 * @author ycl
 */
public class SqlSessionFactoryConfig {

	public static SqlSessionFactory initSqlSessionFactory() {
		Properties properties = new Properties();
		InputStream is = MainApplication.class.getClassLoader().getResourceAsStream("application.properties");
		try {
			properties.load(is);
			if (is != null) {
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		PooledDataSource dataSource = new PooledDataSource();
		dataSource.setDriver(properties.getProperty("datasource.driver"));
		dataSource.setUrl(properties.getProperty("datasource.url"));
		dataSource.setUsername(properties.getProperty("datasource.username"));
		dataSource.setPassword(properties.getProperty("datasource.password"));
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("dev", transactionFactory, dataSource);
		MybatisConfiguration configuration = new MybatisConfiguration(environment);
		configuration.addMappers(properties.getProperty("datasource.mapper-package-name"));
		configuration.setLogImpl(StdOutImpl.class);
		return new MybatisSqlSessionFactoryBuilder().build(configuration);
	}
}
